package com.cy.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.cy.bean.UserList;
import com.cy.util.ConnectionFactory;

public class AddUserDaoImpl implements AddUserDao {

	@Override
	public boolean findUsername(String username) {
		Connection conn = ConnectionFactory.getConnection();
		PreparedStatement psmt = null;
		ResultSet rs = null;
		boolean flag = true;
		try {
			String sql = "select id from user where username=?";
			psmt = conn.prepareStatement(sql);
			psmt.setString(1, username);
			rs = psmt.executeQuery();
			while (rs.next()) {
				if (rs.getInt("id") > 0) {
					flag = false;
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionFactory.close(conn, psmt, rs);
		}
		return flag;
	}

	@Override
	public boolean addUser(UserList user) {
		Connection conn = ConnectionFactory.getConnection();
		PreparedStatement psmt = null;
		int result = 0;
		boolean flag = false;
		try {
			String sql = "insert into user (name,sex,age,username,password,email,state) value (?,?,?,?,?,?,?)";
			psmt = conn.prepareStatement(sql);
			psmt.setString(1, user.getName());
			psmt.setInt(2, user.getSex());
			psmt.setInt(3, user.getAge());
			psmt.setString(4, user.getUsername());
			psmt.setString(5, user.getPassword());
			psmt.setString(6, user.getEmail());
			psmt.setInt(7, user.getState());
			result = psmt.executeUpdate();
			if (result == 1) {
				flag = true;
			} else {
				flag = false;
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionFactory.close(conn, psmt, null);
		}
		return flag;
	}

}
